/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package korekosystem.vista;

import java.awt.Point;
import java.awt.event.ItemEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import javax.persistence.*;
import javax.swing.JOptionPane;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableModel;
import korekosystem.modelo.Cobro;
import korekosystem.modelo.Cliente;
import korekosystem.modelo.Vendedor;
import korekosystem.DatePicker;
import korekosystem.ObservingTextField;
import net.coderazzi.filters.gui.TableFilterHeader;
import javax.persistence.Query;
import javax.swing.JComboBox;
import javax.swing.table.TableModel;

/**
 *
 * @author Santiago
 */
public class ABMCobro extends javax.swing.JInternalFrame {

    @PersistenceContext
    EntityManager entityMgr;
    
    Cobro cobro;
    
    SimpleDateFormat formatoFecha; 
    
   
    /**
     * Creates new form ABMCobro
     */
    public ABMCobro() {
        
        initComponents();        
                
        TableFilterHeader filterHeader = new TableFilterHeader(jTable1);
        
        //Creación de un SimpleDateFormat para la extracción de información de los
        //textfields
        formatoFecha = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
        formatoFecha.setLenient(true);
                
        this.addInternalFrameListener(new InternalFrameAdapter() {
            
            // Cierra el entityManager cuando se cierra
            // la ventana
            @Override
            public void internalFrameClosed(InternalFrameEvent ev) {
                if (entityMgr != null && entityMgr.isOpen()) {
                    entityMgr.close();
                }
            }
            // Se reescribe el evento cuando se abre la ventana
            // para que instancie el entityManager
            @Override
            public void internalFrameOpened(InternalFrameEvent ev) {
                ABMCobro estaVentana =
                        (ABMCobro) ev.getSource();
                try {
                    entityMgr = Persistence
                            .createEntityManagerFactory("KorekoSystemPU")
                            .createEntityManager();

                } catch (Exception e) {
                    JOptionPane.showMessageDialog(estaVentana,
                            "Error al inciar el motor de persistencia\n [" +
                            e.getMessage() + "]");
                    estaVentana.dispose();
                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        clienteComboBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        saldoLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        montoText = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        vendedorComboBox = new javax.swing.JComboBox();
        guardarButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        fechaButton = new javax.swing.JButton();
        fechaPagoText = new korekosystem.ObservingTextField();

        setTitle("ABMCobro");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Cliente:");

        clienteComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        clienteComboBox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                clienteComboBoxMouseClicked(evt);
            }
        });
        clienteComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                clienteComboBoxItemStateChanged(evt);
            }
        });
        clienteComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clienteComboBoxActionPerformed(evt);
            }
        });

        jLabel4.setText("Saldo:");

        saldoLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(clienteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(176, 176, 176)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(saldoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(67, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(saldoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(clienteComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)))
                .addContainerGap(32, Short.MAX_VALUE))
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "", "id", "Fecha de Pagos Pendientes"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.Object.class, java.lang.Object.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.setColumnSelectionAllowed(true);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.getColumnModel().getColumn(1).setMinWidth(0);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(0);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(0);

        jLabel2.setText("Monto a pagar:");

        jLabel3.setText("Vendedor:");

        vendedorComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        vendedorComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                vendedorComboBoxActionPerformed(evt);
            }
        });

        guardarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/guardar.png"))); // NOI18N
        guardarButton.setText("Guardar");
        guardarButton.setEnabled(false);
        guardarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                guardarButtonMouseClicked(evt);
            }
        });
        guardarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarButtonActionPerformed(evt);
            }
        });

        jLabel5.setText("Fecha de Pago:");

        fechaButton.setText("...");
        fechaButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fechaButtonMouseClicked(evt);
            }
        });

        try {
            fechaPagoText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(guardarButton))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(70, 70, 70)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel2))
                        .addGap(31, 31, 31)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(montoText)
                            .addComponent(fechaPagoText, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(50, 50, 50)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(vendedorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(fechaButton, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(montoText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(vendedorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(fechaButton)
                    .addComponent(fechaPagoText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
                .addComponent(guardarButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clienteComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clienteComboBoxActionPerformed
        // TODO add your handling code here: 
    }//GEN-LAST:event_clienteComboBoxActionPerformed

    private void vendedorComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vendedorComboBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_vendedorComboBoxActionPerformed

    private void guardarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_guardarButtonMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_guardarButtonMouseClicked

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        // TODO add your handling code here:
        llenarCBCliente();
        llenarCBVendedor();     
        limpiarFormulario();
    }//GEN-LAST:event_formInternalFrameOpened

    private void clienteComboBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clienteComboBoxMouseClicked
        // TODO add your handling code here:  
    }//GEN-LAST:event_clienteComboBoxMouseClicked

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // esto sirve para que efectivamente tome en cuenta solo los
        // clicks en la primera columna (la columna de seleccion)
        Point p = evt.getPoint();
        if (jTable1.columnAtPoint(p) == 0){
            // Recorremos toda la tabla, buscando los seleccionados
            // guardamos el numero de elementos seleccionados
            // si es uno solo, cargamos en vendedor.
            TableModel tm = jTable1.getModel();
            int selectcount = 0;
            int selectindex = 0;
            for (int i=0; i < tm.getRowCount(); i++ ){
                if( (Boolean) tm.getValueAt(i, 0) == true){
                    selectcount++;
                    selectindex = i;
                }

            }

            if(selectcount == 1) {                
                cobro = (Cobro)tm.getValueAt(selectindex, 1);
                guardarButton.setEnabled(true);                
            } else {
                guardarButton.setEnabled(false);
                cobro = null;
            }           
        }        
    }//GEN-LAST:event_jTable1MouseClicked

    /*Desabilita el boton guardar y borra los campos cada vez que se elige un cliente distinto*/
    private void clienteComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_clienteComboBoxItemStateChanged
        // TODO add your handling code here:              
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            montoText.setText("");
            guardarButton.setEnabled(false);
            vendedorComboBox.setSelectedIndex(-1);
            saldoLabel.setText("");
            
            JComboBox cb = (JComboBox) evt.getSource();
        
            Cliente test = (Cliente) cb.getSelectedItem();        
            if(test != null) {
                System.out.println("Cantidad de Cobro: " + test.getCobroList().size() );
                System.out.println("...." + test.getId());
                saldoLabel.setText(String.valueOf(test.getSaldo()));
                recargarTabla(test);
            }            
        }
    }//GEN-LAST:event_clienteComboBoxItemStateChanged

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        // TODO add your handling code here:
        Cliente cliente = (Cliente) clienteComboBox.getSelectedItem();
        Vendedor vendedor = (Vendedor) vendedorComboBox.getSelectedItem();
        
        // Avisamos que ciertos campos no pueden ser nulos
        if(cliente == null){
            JOptionPane.showMessageDialog(this, "Debe seleccionar un cliente.");
            return;
        } 
        if (vendedor == null){
            JOptionPane.showMessageDialog(this, "Debe seleccionar un vendedor.");
            return;
        }
        if (montoText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "El monto a pagar no puede ser nulo.");
            montoText.requestFocus();
            return;
        }
        if (cliente.getSaldo() < new Long(montoText.getText())) {
            JOptionPane.showMessageDialog(this, "El monto a pagar no puede ser mayor al saldo.");
            montoText.setText("");
            montoText.requestFocus();
            return;
        }
        if (cliente.getSaldo() > new Long(montoText.getText()) && ultimoCobro(cliente)){
            JOptionPane.showMessageDialog(this, "El monto a pagar es menor al saldo, y es el ultimo cobro.\n"
                    + "Debe cancelar su saldo.");
            montoText.setText("");
            montoText.requestFocus();
            return;
        }      
        if (cobro == null){
            JOptionPane.showMessageDialog(this, "Debe seleccionar un Pago Pendiente.");
            return;
        }
        
        if (fechaPagoText.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "La fecha de pago no puede ser nula.");
            fechaButton.requestFocus();
            return;
        }

        EntityTransaction tr = null;
        try {
            
            tr = entityMgr.getTransaction();
            tr.begin();

            //Modificamos el cobro
            //cobro.setFechapago(new Date());
            cobro.setFechapago(formatoFecha.parse(fechaPagoText.getText()));
            cobro.setMonto(new Long(montoText.getText()));
            cobro.setPendiente(false);
            cobro.setVendedor(vendedor);
            cliente.setSaldo(cliente.getSaldo() - cobro.getMonto());
            
            entityMgr.merge(cliente);
            entityMgr.merge(cobro);
                       
            tr.commit();
            JOptionPane.showMessageDialog(this, "Cambios guardados con exito!");
        }catch (Exception e) {
            if (tr != null && tr.isActive()) {
                tr.rollback();
            }
            JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                        e.getMessage() + "]");
            e.printStackTrace();
        }finally {
            cobro = null;
            limpiarFormulario();
            comprobarCobros(cliente);           
        }
        
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void fechaButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fechaButtonMouseClicked
        
        //En este lugar se crea el calendario que aparece al hacer clic en el 
        //botón fechaButton
        //String lang = null;
        //lang = "PY";
        final Locale locale = Locale.getDefault();
        //final Locale locale = getLocale(lang);
        DatePicker dp = new DatePicker(fechaPagoText, locale);
        //previous selected date
        Date selectedDate = dp.parseDate(fechaPagoText.getText());
        dp.setSelectedDate(selectedDate);
        dp.start(fechaPagoText);
        
    }//GEN-LAST:event_fechaButtonMouseClicked
   
    //Método para hallar el estilo de fecha correspondiente a cada país
    //Sin utilizar por el momento
    private Locale getLocale(String loc){
        
        if(loc != null && loc.length() > 0){
            return new Locale("es",loc);
        }
        else{
            return Locale.US;
        }
    }
    
    
    //Llena el clienteComboBox con los correspondientes clientes que posean deudas
    private void llenarCBCliente() {
        clienteComboBox.removeAllItems();
        if ( entityMgr.isOpen()) {
                try {
                        javax.persistence.Query q = entityMgr.createNamedQuery("Cliente.findByActivo");
                        List<Cliente> result = q.getResultList();

                        for (Cliente c: result){
                            clienteComboBox.addItem(c);
                            Cliente test = (Cliente) clienteComboBox.getItemAt(clienteComboBox.getItemCount()-1);
                            System.out.println(test.getId());                                
                        }
                }
                catch (NoResultException  ignorada) {}
                catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                            e.getMessage() + "]");
                    e.printStackTrace();
                }     
        }
    }
    
    //Llena el vendedorComboBox con los vendedores que posee la compañía
    private void llenarCBVendedor() {
        vendedorComboBox.removeAllItems();    
        if ( entityMgr.isOpen()) {
                try {
                        javax.persistence.Query q = entityMgr.createNamedQuery("Vendedor.findAll");
                        List<Vendedor> result = q.getResultList();

                        for (Vendedor v: result){
                            vendedorComboBox.addItem(v);
                            Vendedor test = (Vendedor) vendedorComboBox.getItemAt(vendedorComboBox.getItemCount()-1);
                            System.out.println(test.getId());

                        }                        
                }
                catch (NoResultException  ignorada) {}
                catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                            e.getMessage() + "]");
                    e.printStackTrace(); 
                }
        }
    }
    
    //En caso de cualquier modificación hecha se recarga la tabla para mostrar la
    //información actualización
    private void recargarTabla (Cliente c){
        try{
            Query q = entityMgr.createQuery("select o from Cobro o " +
                                        "where o.cliente = :cliente " +
                                            "and o.pendiente = true");
            q.setParameter("cliente", c);          
            List<Cobro> result = q.getResultList();            
            // se obtiene la referencia al modelo de datos
            DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
            // se descartan la filas existentes
            tm.setRowCount(0);

            // se añaden los datos obtenidos si es que existen
            // cada fila recuperada es un array de Object[]
            System.out.println("Ya tengo los resultados supuestamente");
            SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
            for (Cobro cob : result) {
                System.out.println("-->"+cob);
                // Agregamos a un vector las propiedades
                Vector v = new Vector();
                v.add(false);
                String f = formato.format(cob.getFecha());
                v.add(cob);
                v.add(f);

                // Agregamos ese vector como columna
                tm.addRow(v);
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
                    this.dispose();
        }
    }
    
    private void limpiarFormulario() {
        montoText.setText("");        
        saldoLabel.setText("");
        clienteComboBox.setSelectedIndex(-1);
        vendedorComboBox.setSelectedIndex(-1);
        guardarButton.setEnabled(false);
        // se obtiene la referencia al modelo de datos
        DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
        // se descartan la filas existentes
        tm.setRowCount(0);
    }
    
    private void comprobarCobros(Cliente cliente) {         
            EntityTransaction tr = null;
            if (cliente.getSaldo() == 0 ){

                    Query q = entityMgr.createQuery("select o from Cobro o " +
                                                "where o.cliente = :cliente " +
                                                    "and o.pendiente = true");
                    q.setParameter("cliente", cliente);
                    List<Cobro> result = q.getResultList();
                    try{
                        tr = entityMgr.getTransaction();
                        tr.begin();
                        for (Cobro c : result){
                            c.setPendiente(false);
                            c.setFechapago(new Date());
                            entityMgr.merge(c);
                        }
                        tr.commit();
                    }catch (Exception e) {
                        if (tr != null && tr.isActive()) {
                            tr.rollback();
                        }
                        JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                                    e.getMessage() + "]");
                        e.printStackTrace();
                    }
            }   
    }
    
    private static boolean ultimoCobro (Cliente cliente){
        int count = 0;
        for(Cobro cob: cliente.getCobroList()) {
            if (cob.getPendiente()){
                count++;
            }
        }
        if (count == 1) {
            return true;
        }else return false;
    }      
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox clienteComboBox;
    private javax.swing.JButton fechaButton;
    private korekosystem.ObservingTextField fechaPagoText;
    private javax.swing.JButton guardarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField montoText;
    private javax.swing.JLabel saldoLabel;
    private javax.swing.JComboBox vendedorComboBox;
    // End of variables declaration//GEN-END:variables
}
